有時候可能會遇到要驗證元素全部符合特定條件的時候,這時候並不推薦使用for-in
for (final item in items) {
if (item.length < 5) {
return false;
}
}
return true;
every()
可以讓程式更簡潔return items.every((item) => item.length >= 5);
any()
:當至少有一個元素符合條件時回傳trueevery()
:當全部元素符合條件時回傳true
void main() {
const items = ['Salad', 'Popcorn', 'Toast'];
if (items.any((item) => item.contains('a'))) {
print('At least one item contains "a"');
}
if (items.every((item) => item.length >= 5)) {
print('All items have length >= 5');
}
}
At least one item contains "a"
All items have length >= 5
var evenNumbers = numbers.where((number) => number.isEven);
for (final number in evenNumbers) {
print('$number is even');
}
以上程式碼是在篩選出全部屬於偶數的元素
takeWhile()
會傳回元素直到出現第一個不符合的元素就停止,而skipWhile()
是直到出現第一個不符合的元素才會return第一個不符合條件的元素和後面所有元素
void main() {
const numbers = [1, 3, -2, 0, 4, 5];
var numbersUntilZero = numbers.takeWhile((number) => number != 0);
print('Numbers until 0: $numbersUntilZero');
var numbersStartingAtZero = numbers.skipWhile((number) => number != 0);
print('Numbers starting at 0: $numbersStartingAtZero');
}
Numbers until 0: (1, 3, -2)
Numbers starting at 0: (0, 4, 5)
參考資料:
https://dart.dev/codelabs/iterables#filtering